package com.xl.rentkeeper.business;

import com.squareup.wire.Wire;
import com.xl.fuse.protos.heartbeat.KeepAlive;
import com.xl.fuse.protos.packet.Packet;
import com.xl.rentkeeper.log.QLog;
import com.xl.rentkeeper.mgr.ThreadManager;
import com.xl.rentkeeper.net.NetEngine;
import com.xl.rentkeeper.net.Request;

/**
 * Created by Administrator on 2015/7/15.
 */
public class KeepAliveLogic extends BaseLogic{
    private static KeepAliveLogic sIns;
    public static KeepAliveLogic getInstance() {
        if (sIns == null) {
            synchronized (KeepAliveLogic.class) {
                if (sIns == null) {
                    sIns = new KeepAliveLogic();
                }
            }
        }
        return  sIns;
    }

    Wire wire = new Wire();

    public void doHB() {
        ThreadManager.getInstance().runOnUiThread(keepAlive,1000);
    }


    Runnable keepAlive = new Runnable() {
        @Override
        public void run() {
            if(!UserLogic.getInstance().isLogin()) {
                return;
            }
            KeepAlive alive = new KeepAlive.Builder().ts(System.currentTimeMillis() / 1000).build();
            sendReq(CMD_CONN_HB,alive,null);
        }
    };

    @Override
    public void onResp(Request req, Packet resp) {
        if (resp.ret == 0) {
            QLog.d(this, "heartbeat success");
            KeepAlive sAlive = null;
            try {
                sAlive = wire.parseFrom(SecurityLogic.getInstance().decodeEBody(resp),KeepAlive.class);
                ConfigLogic.getInstance().saveServerTs((KeepAlive) req.oriPb, sAlive);
                QLog.d(this, "client:" + req.oriPb + " server:" + sAlive);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            NetEngine.getInstance().onError(new RuntimeException("heart beat fail,ret=="+resp.ret));
        }
    }
}
